package top.jlzhou.key.controller;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import top.jlzhou.R;
import top.jlzhou.key.entity.Reg;
import top.jlzhou.key.service.RegService;
import top.jlzhou.key.service.SoftService;
import top.jlzhou.tools.sms.SmsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

/**
 * <p>
 * 注册码信息 前端控制器
 * </p>
 *
 * @author J.L.Zhou
 * @since 2018-10-03
 */
@Controller
@RequestMapping("/")
public class RegController {

	
	@Autowired
	private RegService service;
	
	@Autowired
	private SoftService softService;
	
	@Autowired
	private SmsService smsService;
	

	
	
	@RequestMapping(value="index")
	public String doIndex(String key,Integer id,Model model){
		if(key==null||"".equals(key)||id==null){
			model.addAttribute("error", "请从软件中进入注册，否则无效!");
			return "index-error";
		}
		
		
		return "index";
	}
	
	@RequestMapping(value="reg",method=RequestMethod.POST)
	@ResponseBody
	public R doReg(Reg reg,String code){
		try{
			if(!smsService.check(reg.getRegTel(), code)){
				return R.error("验证码错误！");
			}
			service.reg(reg);
			return R.ok().put("soft", softService.getById(reg.getSoftId())).put("reg", reg);
		}catch(Exception ex){
			return R.error(ex.getMessage());
		}
	}
	
	@RequestMapping(value="send-code",method=RequestMethod.POST)
	@ResponseBody
	public R doSendCode(String tel,Integer id){
		if ( service.exists(tel, id)) {
			return R.error("该手机号码已经注册过该软件了");
		}
		try{
			smsService.send(tel);
			return R.ok();
		}catch(Exception ex){
			return R.error(ex.getMessage());
		}
	}
	
	
}

